home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
NetNews Offline 2
/
NetNews Offline Volume 2.iso
/
news
/
comp
/
std
/
c
/
610
< prev
next >
Wrap
Text File
|
1996-08-06
|
2KB
|
76 lines
Path: lyra.csx.cam.ac.uk!jkb
From: jkb@mrc-lmb.cam.ac.uk (James Bonfield)
Newsgroups: comp.std.c
Subject: Restrictions on qsort compare function?
Date: 20 Mar 1996 09:56:41 GMT
Organization: MRC Laboratory of Molecular Biology, Cambridge UK
Distribution: world
Message-ID: <4iokop$h4p@lyra.csx.cam.ac.uk>
NNTP-Posting-Host: alf2.mrc-lmb.cam.ac.uk
Are there any limitations on what the sort function passed over to qsort can
do or return? I know it's meant to return < 0, 0 or > 0 for the various
compare operations, but which you return is purely up to your own comparison
system.
On tracking down a bug in some old code I noticed that we had the
compare function returning something like "a > b" instead of "b - a".
Now this is obviously some silly bug in our coding, but "a > b" is still
a valid sort function surely? The reason I ask is that this that such
functions appear to make the Irix 5.3 qsort() function underflow the
passed array. Please check the following function to verify that I
haven't done something daft.
#include <stdio.h>
#include <stdlib.h>
static int sort_func(const void *pa, const void *pb)
{
const int *a = (int *)pa;
const int *b = (int *)pb;
return *a > *b;
}
#define NUM_ELE 10
int main() {
int i;
int crashme; /* removing this line fixes things! */
int sortme[NUM_ELE];
srand(time(NULL));
for (i=0; i<NUM_ELE; i++) {
sortme[i] = rand()%100+50;
}
qsort((void *)sortme, NUM_ELE, sizeof(int), sort_func);
return 0;
}
Adding some debugging information to this and printing up the array
before and after sorting (including the values (666) immediately above
and below the array) shows that the contents of memory outside of the
array actually get swapped with memory inside the array. I can make it
overflow too. My understanding of this is that qsort() ought to be able
to handle any sort function, even if it's something as dumb as
(rand()%3)-1.
Anyway, my debugging output shows:
666 < 98 61 57 50 125 73 111 103 131 136 > 666
qsort it...
50 < 57 61 73 98 666 103 111 125 131 136 > 666
Anyone seen this before? I've checked SunOS4, SunOS5, DEC OSF/3.0 and
Irix 5.3 and so far only found Irix to be deficient.
Bye for now,
James
--
James Bonfield (jkb@mrc-lmb.cam.ac.uk) Tel: 01223 402499 Fax: 01223 412282
Medical Research Council - Laboratory of Molecular Biology,
Hills Road, Cambridge, CB2 2QH, England.